import React, { Component } from 'react';
import { connect, } from 'react-redux';
import moment from 'moment'
import request from '../api/request'
import { SET_USER, SET_GAME_INFO } from '../actions/actions'
import { getImgUrl, getUserInfo, openSherd, setSherd } from '../utils/utils'

import Alert from '../components/Alert'


class Questions extends Component {
  constructor(props) {
    super(props)
    this.state = {
      status: false,
      progress: 0,
      show: false,
      integralShow: false,
      type: '',
      list: [],
      answer: [],
      isBetween: false,
      beforeUser: {},
      sign: {
        day: '',
        integral: ''
      }
    }
  }

  start() {
    const { user, dispatch, gameInfo } = this.props
    this.setState({
      beforeUser: user
    })
    let isBetween = moment().isBetween(gameInfo.timeStart, gameInfo.timeEnd, 'days') || moment().isSame(gameInfo.timeStart, 'days') || moment().isSame(gameInfo.timeEnd, 'days')
    if (isBetween) {
      if (user.answer > 0) {
        request.startQuestions({
          openid: user.openid
        }).then(signres => {
          console.log(signres)
          // if (!moment().isSame(user.prevLoginDate, 'days')) {
          if (signres.success) {
            this.setState({
              type: 'sign',
              show: true,
              sign: signres.data
            })
          }
          // }
          let collection = 1
          if (user.isShare && user.answer == 2) {
            collection = 1
          } else if (user.isShare) {
            collection = 2
          }
          request.dailyQuestions({
            collection
          }).then(res => {
            console.log(res)
            getUserInfo(dispatch, { openid: user.openid })
            this.setState({
              status: true,
              list: res.data
            })
          })
        })
      } else {
        this.setState({
          type: 'end',
          show: true,
          status: true,
        })
      }
    } else {
      this.setState({
        status: true,
      })
    }
  }

  componentDidMount() {
    const { user, gameInfo, dispatch } = this.props
    setSherd(user.openid, dispatch)
    request.projectInfo({ id: 1 }).then(res => {
      dispatch({
        type: SET_GAME_INFO,
        data: res.data
      })
      this.start()
    })
  }


  verifyAnswer(question, answer) {
    let progress = this.state.progress
    let answerAry = this.state.answer
    const { user } = this.props
    request.verifyAnswer({
      id: question.id,
      openid: user.openid,
      answer,
    }).then(res => {
      console.log(res)
      progress++
      this.setState({
        progress
      })
      answerAry.push(res.data)
      if (res.data) {
        this.setState({
          type: 'success',
          show: true,
          answer: answerAry
        })
      } else {
        this.setState({
          type: 'error',
          show: true,
          answer: answerAry
        })
      }
    })
  }

  openIntegralList = () => {
    const { integralShow } = this.state
    this.setState({
      integralShow: !integralShow
    })
  }

  onClose = () => {
    const { user: { openid }, dispatch } = this.props
    const { show, progress, list, type } = this.state
    console.log(progress >= list.length - 1, type != 'tzjs', type)
    if (progress > list.length - 1 && type != 'tzjs') {
      this.setState({
        type: 'tzjs',
        show: true
      })
      request.getUserInfo({
        openid
      }).then(res => {
        dispatch({
          type: SET_USER,
          data: res.data
        })
      })
    } else {
      this.setState({
        show: !show
      })
    }
  }

  renderHomeBtns() {
    const { dispatch } = this.props
    return (
      <div className="render-home-btns">
        <div className="home-btns">
          <div className="go" onClick={() => this.props.history.push('/questions/')}><img src={require('../static/image/btn-goHome.png')} alt="" /></div>
          <div className="jinnang" onClick={this.openIntegralList}>积分详情&gt;&gt;</div>
        </div>
        <div className="home-cell">
          <div className="icon" onClick={() => this.props.history.push('/questions/list')}><img src={require('../static/image/icon-paihangbang.png')} alt="" /></div>
          <div className="icon" onClick={() => openSherd(dispatch)}><img src={require('../static/image/icon-fxhaoyou.png')} alt="" /></div>
        </div>
      </div>
    )
  }

  renderQuestions() {
    const { user, gameInfo } = this.props
    const { status, beforeUser, list, progress } = this.state
    if (status && beforeUser.openid) {
      let isBetween = moment().isBetween(gameInfo.timeStart, gameInfo.timeEnd, 'days') || moment().isSame(gameInfo.timeStart, 'days') || moment().isSame(gameInfo.timeEnd, 'days')
      // moment().isBetween('2019-06-18', '2019-06-20', 'days') || moment().isSame('2019-06-18', 'days') || moment().isSame('2019-06-20', 'days')
      if (!isBetween) {
        return (
          <div className="questions-cotnent" >
            <div className="questions-tol-title">
              <img src={require('../static/image/text-dati.png')} alt="" />
              {/* <p className="subtitle">请{gameInfo.timeStart}至{gameInfo.timeEnd}参加活动</p> */}
            </div>
            {this.renderHomeBtns()}
          </div>
        )
      }

      if (beforeUser.answer <= 0) {
        return (
          <div className="questions-cotnent" >
            <div className="questions-tol-title">
              <p className="title">今日挑战结束</p>
              <p className="subtitle">分享好友可再多一次答题机会哦！</p>
            </div>
            {this.renderHomeBtns()}
          </div>
        )
      }
      if (list.length <= 0) {
        return (
          <div className="questions-cotnent" >
            <div className="questions-tol-title">
              <p className="title">后台未设置问题</p>
              <p className="subtitle">请设置问题后重新进入页面</p>
            </div>
            {this.renderHomeBtns()}
          </div>
        )
      }
      if (progress <= list.length - 1) {
        return list.map((item, index) => {
          if (progress === index) {
            return (
              <div className="questions-cotnent" key={index}>
                <div className="questions-cotnent-title">
                  <p className="title">{index + 1}.{item.describe}</p>
                  <img src={getImgUrl(item.describePic)} alt="" />
                  <p className="subtitle">{item.title}</p>
                </div>
                <div className="questions-cotnent-options">
                  {item.optionA || item.optionAPic ? (
                    <div className="questions-cotnent-option" onClick={() => this.verifyAnswer(item, 'A')}>
                      <div className="questions-cotnent-option-hd">
                        <p>A：</p>
                      </div>
                      <div className="questions-cotnent-option-bd">
                        {item.optionA ? (<p>{item.optionA}</p>) : null}
                        {item.optionAPic ? (<img src={getImgUrl(item.optionAPic)} alt="" />) : null}
                      </div>
                    </div>
                  ) : null}
                  {item.optionB || item.optionBPic ? (
                    <div className="questions-cotnent-option" onClick={() => this.verifyAnswer(item, 'B')}>
                      <div className="questions-cotnent-option-hd">
                        <p>B：</p>
                      </div>
                      <div className="questions-cotnent-option-bd">
                        {item.optionB ? (<p>{item.optionB}</p>) : null}
                        {item.optionBPic ? (<img src={getImgUrl(item.optionBPic)} alt="" />) : null}
                      </div>
                    </div>
                  ) : null}
                  {item.optionC || item.optionCPic ? (
                    <div className="questions-cotnent-option" onClick={() => this.verifyAnswer(item, 'C')}>
                      <div className="questions-cotnent-option-hd">
                        <p>C：</p>
                      </div>
                      <div className="questions-cotnent-option-bd">
                        {item.optionC ? (<p>{item.optionC}</p>) : null}
                        {item.optionCPic ? (<img src={getImgUrl(item.optionCPic)} alt="" />) : null}
                      </div>
                    </div>
                  ) : null}
                  {item.optionD || item.optionDPic ? (
                    <div className="questions-cotnent-option" onClick={() => this.verifyAnswer(item, 'D')}>
                      <div className="questions-cotnent-option-hd">
                        <p>D：</p>
                      </div>
                      <div className="questions-cotnent-option-bd">
                        {item.optionD ? (<p>{item.optionD}</p>) : null}
                        {item.optionDPic ? (<img src={getImgUrl(item.optionDPic)} alt="" />) : null}
                      </div>
                    </div>
                  ) : null}
                </div>
              </div>
            )
          }
        })
      } else {
        return (
          <div className="questions-cotnent" >
            <div className="questions-tol-title">
              <p className="title">今日挑战结束</p>
              <p className="subtitle">分享好友可再多一次答题机会哦！</p>
            </div>
            {this.renderHomeBtns()}
          </div>
        )
      }
    }
    return (
      <div className="questions-cotnent" >
        <div className="questions-tol-title">
          <img src={require('../static/image/text-dati.png')} alt="" />
          {/* <p className="subtitle">请{gameInfo.timeStart}至{gameInfo.timeEnd}参加活动</p> */}
        </div>
        {this.renderHomeBtns()}
      </div>
    )
  }

  render() {
    const { user } = this.props
    const { status, show, type, integralShow, beforeUser, sign } = this.state
    console.log(this)
    return (
      <div className="questions">
        <img className="questions-title" src={require('../static/image/questions-bg.png')} alt="" />
        {this.renderQuestions()}
        <Alert show={show} type={type} sign={sign} integral={user.integral} onClose={this.onClose} />
        <Alert show={integralShow} type={'integral'} integral={user.integral} onClose={this.openIntegralList} >
          <div className="integralList">
            <span className="integral">总积分：{user.integral}</span>
            <ul >
              {user.integralList && user.integralList.map((item, index) => {
                let isDay = moment().isSame(moment(item.date).format('YYYY-MM-DD'), 'day')
                if (isDay) {
                  return (
                    <li key={index}>
                      {item.type === 1 ? <span>正确答题</span> : null}
                      {item.type === 2 ? <span>连续答题</span> : null}
                      {item.type === 3 ? <span>每日分享</span> : null}
                      {item.type === 4 ? <span>邀请好友</span> : null}
                      <span>+{item.integral}</span>
                    </li>
                  )
                }
                return null
              })}
            </ul>
          </div>
        </Alert>
      </div>
    );
  }
}

export default connect(({ user, code, gameInfo }) => ({ user, code, gameInfo }))(Questions);

